<template>
  <div class="app-container" style="padding-top: 5px;">
    <el-tabs v-model="currentTabs">
      <el-tab-pane label="创建收集表" name="template">
        <el-row>
          <el-col :span="6">
            <div class="disFlxAC my-10 addBox" @click="addForm">
              <i class="iconfont el-icon-plus fz-40" />
              <div class="fz-20 pl-10">创建收集表</div>
            </div>
          </el-col>
          <el-col
            :span="6"
            v-for="(item, index) in tempList"
            :key="index"
            class="forBox my-10"
          >
            <div class="disFlxAC" @click="copyTemplate(item)">
              <img :src="item.templateIcon" style="width: 80px; height: 80px" />
              <div class="px-10">
                <div>{{ item.templateName }}</div>
                <div class="color9 pt-5">{{ item.templateDesc }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="数据统计" name="formList">
        <div class="pb-10">
          <el-table :data="tableList">
            <el-table-column label="表单名称" align="center" prop="formTitle" />
            <el-table-column
              label="发起人"
              align="center"
              prop="createUser"
              width="150"
            />
            <el-table-column
              label="收集状态"
              align="center"
              prop="collectStatus"
              width="100"
            >
              <template slot-scope="{ row }">
                <div>{{ collectStatus(row) }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="收集数量"
              align="center"
              prop="collectNum"
              width="100"
            />
            <el-table-column
              label="链接地址"
              align="center"
              prop="httpHead"
              width="100"
            >
              <template slot-scope="{ row }">
                <el-link
                  :underline="false"
                  icon="el-icon-document-copy"
                  v-clipboard:copy="
                    `${row.httpHead}/customForm?formId=${row.formId}&userType=0&collectUserid=${userInfo.userId}`
                  "
                  v-clipboard:success="clipboardSuccess"
                  >复制</el-link
                >
              </template>
            </el-table-column>
            <el-table-column
              label="分享二维码"
              align="center"
              prop="httpHead"
              width="100"
            >
              <template slot-scope="{ row }">
                <el-link
                  :underline="false"
                  icon="el-icon-picture"
                  @click="dwQRCode(row)"
                  >查看</el-link
                >
              </template>
            </el-table-column>
            <el-table-column
              label="发布时间"
              align="center"
              prop="createTime"
              width="180"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="200"
            >
              <template slot-scope="{ row }">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="openEditSet(row)"
                  >修改设置</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="viewUrl(row)"
                  >预览表单</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-tickets"
                  @click="openData(row)"
                  >数据详情</el-button
                >
                <el-button
                  v-if="row.collectStatus !== 1"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="upStatus(row)"
                  >结束收集</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="数据详情" :visible.sync="pShow" width="800px">
      <div class="disFlxJS pb-10">
        <div>
          <span>共{{ pTotal }}份数据</span>
          <span class="pl-5"
            >已勾选<span class="colorZS px-2">{{ selectRows.length }}</span
            >份数据</span
          >
        </div>
        <div>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport('ALL')"
            >全部导出</el-button
          >
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport('CHECKED')"
            >导出已勾选</el-button
          >
        </div>
      </div>
      <el-table
        :data="pList"
        height="50vh"
        ref="multipleTable"
        @select="handleSelectionChange"
        @select-all="handleAllSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="收集人" align="center" prop="collectUser" />
        <el-table-column label="用户姓名" align="center" prop="userName" />
        <el-table-column
          label="提交时间"
          align="center"
          prop="createTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="collectStatus"
          width="80"
        >
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" @click="openUrl(row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="pTotal > 0"
        :total="pTotal"
        :page.sync="pParams.pageNum"
        :limit.sync="pParams.pageSize"
        @pagination="getStatsList"
      />
      <div class="disFlxCC pt-20">
        <el-button type="primary" size="default" @click="pShow = false"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="二维码" :visible.sync="qrcodeShow" width="400px">
      <div class="disFlxCC">
        <div id="qrcode" ref="qrcode"></div>
        <div class="fz-12 color9 linh-50">右键可另存为至本地</div>
        <el-button type="primary" size="default" @click="qrcodeShow = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="修改表单设置" :visible.sync="editSetShow" width="500px">
      <ReleaseSet
        ref="ReleaseSet"
        :editRow="editSetObj"
        @colse="editSetShow = false"
        @confirm="confirmEdit"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getTemplateList,
  getFormList,
  updateFormStatus,
  getFormStatsList,
  updateTemplate,
  exportStatistics,
} from "@/api/customForm/customForm";
import QRCode from "qrcodejs2";
import ReleaseSet from "./build/ReleaseSet.vue";
import { uniqBy, intersectionBy, differenceBy } from "lodash";

export default {
  name: "FormList",
  data() {
    return {
      currentTabs: "template",
      tempList: [], // 模板列表
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      pShow: false,
      pTotal: 0,
      pList: [],
      pParams: {
        formId: "",
        pageNum: 1,
        pageSize: 10,
        userName: "",
      },
      qrcode: "",
      qrcodeShow: false,
      editSetShow: false,
      editSetObj: {},
      selectRows: [], // 数据详情,总共已勾选
    };
  },
  components: {
    ReleaseSet,
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  created() {
    if (this.$route.query.type) {
      this.currentTabs = this.$route.query.type;
    }
    this.getTemp();
    this.getList();
  },
  activated() {
    this.getTemp();
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getTemp() {
      getTemplateList({ pageNum: 1, pageSize: 999, enableState: 1 }).then(
        (response) => {
          this.tempList = response.rows;
        }
      );
    },
    // 查询数据统计列表
    getList() {
      getFormList(this.queryParams).then((response) => {
        this.tableList = response.rows;
        this.total = response.total;
      });
    },
    // 判断手机状态
    collectStatus(row) {
      if (row.collectStatus === 1) {
        return "已结束";
      }
      if (!row.endTime) {
        return "收集中";
      }
      let endTime = Date.parse(new Date(row.endTime));
      let newTime = Date.parse(new Date());
      if (endTime <= newTime) {
        console.log(row, "通过时间判断已结束");
        return "已结束";
      }
      return "收集中";
    },
    // 创建收集表
    addForm() {
      this.$router.push({ path: `/form/build/index?type=2` });
    },
    // 以模板新增收集表
    copyTemplate(item) {
      let url = `/form/build/index?type=2`;
      url += item.templateId ? `&templateId=${item.templateId}` : "";
      url += item.formId ? `&formId=${item.formId}` : "";
      this.$router.push({ path: url });
    },
    // 修改表单收集状态
    upStatus(row) {
      this.$confirm("此操作将停止该表单收集, 是否继续?", "提示", {
        confirmButtonText: "确定停止",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = {
          formId: row.formId,
          collectStatus: 1, // 0收集 1结束
        };
        updateFormStatus(params).then((res) => {
          this.getList();
        });
      });
    },
    // 打开数据详情弹窗
    openData(row) {
      this.pShow = true;
      this.pParams.formId = row.formId;
      this.selectRows = [];
      this.getStatsList();
    },
    // 获取数据详情列表
    getStatsList() {
      getFormStatsList(this.pParams).then((response) => {
        this.pList = response.rows;
        this.pTotal = response.total;

        const currentSelectedRows = intersectionBy(
          response.rows,
          this.selectRows,
          "recordId"
        );
        this.$nextTick(() => {
          currentSelectedRows.forEach((row) => {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          });
        });
      });
    },
    // 打开详情
    openUrl(row) {
      window.open(
        `/customForm?formId=${row.formId}&userType=${row.userType}&collectUserid=${row.collectUserid}&recordId=${row.recordId}`
      );
    },
    // 预览效果
    viewUrl(row) {
      window.open(
        `/customForm?formId=${row.formId}&userType=0&collectUserid=${this.userInfo.userId}&preview=mobileView`
      );
    },
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    dwQRCode(row) {
      this.qrcodeShow = true;
      if (this.$refs["qrcode"] && this.$refs["qrcode"].innerHTML) {
        this.$refs["qrcode"].innerHTML = "";
      }
      this.$nextTick(() => {
        new QRCode("qrcode", {
          width: 200, // 设置宽度，单位像素
          height: 200, // 设置高度，单位像素
          text: `${row.httpHead}/customForm?formId=${row.formId}&userType=0&collectUserid=${this.userInfo.userId}`, // 设置二维码内容或跳转地址
        });
      });
    },
    // 修改表单配置
    openEditSet(row) {
      this.editSetShow = true;
      this.editSetObj = row;
    },
    // 确定修改表单
    confirmEdit(form) {
      let params = {
        updateType: 1, // 编辑类型: 0模板 1表单
        formId: this.editSetObj.formId,
        formType: this.editSetObj.formType, // 表单类型：0模板表单 1自定义表单
        userIds: form.userIds, // 表单指定收集者
        writeLimit: form.writeLimit, // 限填限制：0不限制 1限制
        endTime: form.endTime,
      };
      updateTemplate(params).then((res) => {
        this.$message.success("修改成功");
        this.editSetShow = false;
        this.getList();
      });
    },
    handleSelectionChange(selection, row) {
      this.selectRows = differenceBy(this.selectRows, [row], "recordId"); // 删除当前操作行
      this.selectRows = uniqBy([...this.selectRows, ...selection], "recordId"); // 合并已勾选并去重
    },
    handleAllSelectionChange(selection) {
      if (!selection.length) {
        this.selectRows = differenceBy(this.selectRows, this.pList, "recordId"); // 删除当前页所有行
      } else {
        this.selectRows = uniqBy(
          [...this.selectRows, ...selection],
          "recordId"
        ); // 合并已勾选并去重
      }
    },
    // 导出数据
    handleExport(type) {
      if(!this.pList.length) return
      if (type === "CHECKED" && !this.selectRows.length) {
        this.$message.info("请勾选需要导出的数据");
        return;
      }
      const ids = this.selectRows.map((v) => v.recordId);
      const formId = this.pParams.formId;
      this.download(
        "/system/template/export",
        type === "ALL"
          ? { formId }
          : { formId, recordIds: ids.join(',') },
        `表单收集_${this.parseTime(new Date(),'{y}-{m}-{d}')}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.forBox {
  cursor: pointer;
  border-radius: 5px;
  overflow: hidden;
}
.addBox {
  width: 180px;
  height: 80px;
  margin-right: 10px;
  border: dashed 1px #999999;
  border-radius: 5px;
  justify-content: center;
  cursor: pointer;
  &:hover {
    border-color: #1890ff;
    color: #1890ff;
  }
}
</style>
